package com.enation.app.shop.front.api.appcontroller;

import com.enation.app.shop.core.goods.model.Goods;
import com.enation.app.shop.core.goods.model.Product;
import com.enation.app.shop.core.goods.service.IGoodsManager;
import com.enation.app.shop.core.goods.service.IProductManager;
import com.enation.app.shop.core.order.model.Cart;
import com.enation.app.shop.core.order.service.ICartManager;
import com.enation.app.shop.front.api.appdto.CartDelete;
import com.enation.app.shop.front.api.order.publicmethod.CartPublicMethod;
import com.enation.eop.sdk.utils.StaticResourcesUtil;
import com.enation.framework.action.JsonResult;
import com.enation.framework.util.JsonResultUtil;
import com.enation.framework.util.TestUtil;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 购物车的类
 */
@Scope("prototype")
@Controller
@RequestMapping("/app/cat")
public class CatAppController {
    protected final Logger logger = Logger.getLogger(getClass());

    @Autowired
    private CartPublicMethod cartPublicMethod;
    @Autowired
    private IProductManager productManager;
    @Autowired
    private ICartManager cartManager;
    @Autowired
    private IGoodsManager goodsManager;

    /**
     * 将一个货品添加至购物车。
     * 需要传递productid和num参数
     *
     * @param productid 货品id，int型
     * @num 数量，int 型
     *
     * @return 返回json串
     * result  为1表示调用成功0表示失败 ，int型
     * message 为提示信息
     */
    @ResponseBody
    @RequestMapping(value="/addproduc", produces = MediaType.APPLICATION_JSON_VALUE)
    public JsonResult addProduc(Integer productid, Integer num){

        Product product = productManager.get(productid);
        return cartPublicMethod.addCar(product, num, 0, null);

    }
    /**
     * //购物车list
     * @param userid
     * @return
     */
    @ResponseBody
    @RequestMapping("/getCartList")
    public JsonResult getCatList(Integer userid){
      List<Cart> catslist=cartManager.getCatList(userid);
        List<Map<String, Object>> goodsSmalls = new ArrayList<Map<String, Object>>();
        for (Cart cart:catslist) {
            Map<String, Object> cat = new HashMap<String, Object>();
            cat.put("catid",cart.getCart_id());
            cat.put("goodsid",cart.getGoods_id());
            cat.put("productid", cart.getProduct_id());
            cat.put("price", cart.getPrice());
            cat.put("name", cart.getName());
            cat.put("goodnum",cart.getNum());
            int goodsid=cart.getGoods_id();
            Goods goods=goodsManager.getGoods(goodsid);
            cat.put("thum", StaticResourcesUtil.transformPathapp(goods.getThumbnail()));
//            ParamGroup[] paramList = GoodsTypeUtil.converFormString(goods.getParams());
//            List<GoodsParam> goodsParams=null;
//            try {
//                for (int i=0;i<paramList.length;i++){
//                    goodsParams=paramList[0].getParamList();
//                }
//                for (GoodsParam goodsParam:goodsParams){
//                    if (goodsParam.getName().equals("险种说明")){
//                        cat.put("description",goodsParam.getValue());
//                    }
//                }
//            }catch (Exception e){
//                logger.info("空指针异常");
//            }
            goodsSmalls.add(cat);
        }
        return JsonResultUtil.getObjectMessageJson(goodsSmalls,"购物车list");
    };


    /**
     *  //删除购物车数据
     * @param cartDelete
     * @return
     */
    @ResponseBody
    @RequestMapping("/deletecart")
    public JsonResult deleteCart(@RequestBody CartDelete cartDelete){
        try{
            cartManager.delete(cartDelete.getCartid(),cartDelete.getUserid());
            return JsonResultUtil.getSuccessJson("删除购物项成功");
        }catch(RuntimeException e){
            TestUtil.print(e);
            this.logger.error("删除购物项失败",e);
            return JsonResultUtil.getErrorJson("删除购物项失败");
        }
    }

    /**
     *  //删除购物车数据
     * @param cartid
     * @param userid
     * @return
     */
    @ResponseBody
    @RequestMapping("/deletecartarray")
    public JsonResult deleteCart(int [] cartid,int userid){
        try{
//            String cartid=re.getParameter("cartid").toString();
            cartManager.delete(cartid,userid);
            return JsonResultUtil.getSuccessJson("删除购物项成功");
        }catch(RuntimeException e){
            TestUtil.print(e);
            this.logger.error("删除购物项失败",e);
            return JsonResultUtil.getErrorJson("删除购物项失败");
        }
    }


    /**
     * //更新购物车数量
     * @param cartid
     * @param num
     * @param productid
     * @param userid
     * @return
     */
    @ResponseBody
    @RequestMapping("/updategoodsnum")
    public JsonResult updateNum(Integer cartid,
                                Integer num,
                                Integer productid,
                                Integer userid){
        try{
            Product product=productManager.get(productid);
            Integer store=product.getEnable_store();
            if (store>num){
                cartManager.updateNum("app",cartid,num,userid);
            }else {
                JsonResultUtil.getErrorJson("库存不足");
            }
            return JsonResultUtil.getSuccessJson("更新成功");
        }catch(RuntimeException e){
//			TestUtil.print(e);
            this.logger.error("更新购物车数量出现意外错误", e);
            return JsonResultUtil.getErrorJson("更新购物车数量出现意外错误:"+e.getMessage());
        }
    }


    /**
     *     //清空购物车
     * @param userid
     * @return
     */
    @ResponseBody
    @RequestMapping("/cleancart")
    public JsonResult clean(Integer userid){
        try {
            cartManager.clean(userid);
            return JsonResultUtil.getSuccessJson("清空购物车成功");
        }catch (Exception e){
            this.logger.error("清空购物车出错");
            return JsonResultUtil.getErrorJson("清空购物车出错");
        }
    }



}
